package com.restkeeper.controller;

import com.aliyun.oss.OSSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@Api(tags = { "图片上传通用接口" })
public class FileUploadController {
	@Value("${bucketName}")
	private String bucketName;

	@Value("${spring.cloud.alicloud.oss.endpoint}")
	private String endpoint;

	@Value("${spring.cloud.alicloud.access-key}")
	private String accessKey;

	@Value("${spring.cloud.alicloud.secret-key}")
	private String secretkey;

	@Autowired(required = false)
	private OSSClient ossClient;

	@PostMapping(value = "/fileUpload")
	@ApiImplicitParam(paramType = "form", dataType = "file", name = "file", value = "上传文件", required = true)
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		if(ossClient==null){
			ossClient =new OSSClient(endpoint,accessKey,secretkey);
		}

		 String fileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
		try {
			ossClient.putObject(bucketName, fileName, file.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("upload file error", e);
		}
		String imagePath = "https://" + bucketName + "."+endpoint+"/"+ fileName;
		return imagePath;
	}

	@PostMapping(value = "/imageUploadResize")
	@ApiImplicitParam(paramType = "form", dataType = "file", name = "file", value = "上传文件", required = true)
	public String imageUploadResize(@RequestParam("file") MultipartFile file) {
		if(ossClient==null){
			ossClient =new OSSClient(endpoint,accessKey,secretkey);
		}
		String fileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
		try {
			ossClient.putObject(bucketName, fileName, file.getInputStream());
		} catch (Exception e) {
			log.error("upload file error", e);
		}
		String imagePath = "https://" + bucketName + "."+endpoint+"/"+ fileName+"?x-oss-process=image/resize,m_fill,h_100,w_200";
		return imagePath;
	}
}
